package com.vladimirkolarevic.eventplanner.spring_hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.transaction.annotation.Transactional;

import com.vladimirkolarevic.eventplanner.Event;
import com.vladimirkolarevic.eventplanner.User;
import com.vladimirkolarevic.eventplanner.beans.UserBean;
import com.vladimirkolarevic.eventplanner.service.MembershipsService;

public class MembershipDAO implements MembershipsService{

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@Transactional
	public Long addUser(User user) {
		// TODO Auto-generated method stub
		return (Long) sessionFactory.getCurrentSession().save(user);
	}
	@Transactional
	public boolean changeUserInfo(User user) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().update(user);
		return true;
	}
	
	@Transactional
	public User findUser(Serializable id) {
		// TODO Auto-generated method stub
		return (User) sessionFactory.getCurrentSession().load(UserBean.class, id);
	}
	
	@Transactional
	public User getUser(User user) {
		// TODO Auto-generated method stub
		Example ue = Example.create(user).excludeProperty("id")
		.excludeProperty("firstName")
		.excludeProperty("secondName")
		.excludeProperty("email")
		.excludeProperty("events")
		.ignoreCase().enableLike(MatchMode.ANYWHERE);
		Criteria crit = sessionFactory.getCurrentSession().createCriteria(UserBean.class).add(ue);
		return (User) crit.uniqueResult();
	}
	@Transactional
	public User getUserByUserName(Serializable username) {
		// TODO Auto-generated method stub
		return (User) sessionFactory.getCurrentSession().createQuery("from UserBean where username = :u")
		.setString("u", (String) username).uniqueResult();
	}

	public void removeUser(User user) {
		// TODO Auto-generated method stub
		
	}
	
	@Transactional
	public List<Event> getEvents(Long id) {
		return ((User) sessionFactory.getCurrentSession().load(UserBean.class, id)).getEvents();
	}

}
